package com.superhelper.common.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.superhelper.common.Consts;
import com.superhelper.common.domain.ExtMsg;
import com.superhelper.common.utils.JsonHelper;
import com.xiaomi.push.sdk.ErrorCode;
import com.xiaomi.xmpush.server.Constants;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;

/**
 * @author duanyunfeng
 * 
 */
public class XiaomiPushService {
    private final String packageName = "com.superhelper";
    private final String appSecret = "sjdudolBORDJTSwsIReslw==";
    private final String iosAppSecret = "a3AAeMsD/jynPwWaEqdgVw==";
    @Value("${online}")
    private Boolean online;

    private static final int RETRY_TIMES = 3;
    private final static Logger LOG = LoggerFactory.getLogger(XiaomiPushService.class);

    private Sender getSender(String device) {

        if (!StringUtils.containsIgnoreCase(device, Consts.Device.IOS)) {
            return new Sender(appSecret);
        }
        return new Sender(iosAppSecret);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.guzhi.service.push.PushService#send(java.lang.String,
     * java.lang.String, java.util.List)
     */
    public boolean push(String title, String content, String playload, final String target, String device, ExtMsg msg) {
        LOG.info("[send] target:{},title:{},content:{},playload:{},device:{},{}", target, title, content, playload,
                device, msg);
        Message message = buildMessage(title, content, playload, device, msg);
        // 指定对别名进行发送
        Sender sender = getSender(device);
        int i = 0;
        boolean returnValue = false;
        // 重试多次保证成功
        while (i++ < 3) {
            try {
                Result result = sender.sendToAlias(message, target, RETRY_TIMES);
                LOG.info("[send] target:{},title:{},result:{}", target, title, result);
                returnValue = ErrorCode.Success.getValue() == result.getErrorCode().getValue();
                break;
            } catch (Exception e) {
                LOG.error("[send] error target:{},{}", target, e);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e1) {
                }
            }
        }
        LOG.info("[send] target:{},title:{},returnValue:{}", target, title, returnValue);
        return returnValue;
    }

    private Message buildMessage(String title, String content, String playload, String device, ExtMsg msg) {
        Constants.useOfficial();
        if (!StringUtils.containsIgnoreCase(device, Consts.Device.IOS)) {
            Message.Builder builder = new Message.Builder().title(title).description(content).payload(playload)
                    .restrictedPackageName(packageName)
                    // 0：通知 1透传
                    .passThrough(1).notifyType(1).timeToLive(1800 * 1000)
                    .extra(Constants.EXTRA_PARAM_SOUND_URI, "android.resource://com.guzhichat/raw/dot"); // 使用默认提示音提示
            if (msg != null) {
                for (String key : msg.getMsg().keySet()) {
                    builder.extra(key, msg.getMsg().get(key));
                }
            }
            return builder.build();
        } else {
            if (online) {
                Constants.useOfficial();
            } else {
                Constants.useSandbox();
            }
            Message.IOSBuilder iosBuilder = new Message.IOSBuilder().description(content).soundURL("sound_msg.mp3") // 消息铃声
                    .badge(1) // 数字角标
                    .category("action") // 快速回复类别
                    .extra("title", title) // 自定义键值对
                    .timeToLive(1800 * 1000);
            if (msg != null) {
                for (String key : msg.getMsg().keySet()) {
                    iosBuilder.extra(key, msg.getMsg().get(key));
                }
            }

            return iosBuilder.build();
        }
    }

    public boolean sendToUser(String title, String playload, final String account, ExtMsg extras) {
        boolean result = this.sendToUserAccount(title, playload, account, "android", extras);
        return result;
    }

    /**
     * userAccount主要适用于用户多点登陆的情况
     * 
     * @param title
     * @param playload
     * @param account
     * @param uuid
     * @param device
     * @param extras
     * @return
     */
    private boolean sendToUserAccount(String title, String playload, final String account, String device,
            ExtMsg extras) {
        Message message = buildMessage(title, title, playload, device, extras);
        // 指定对账号进行发送
        Sender sender = getSender(device);
        int i = 0;
        boolean returnValue = false;
        // 重试多次保证成功
        while (i++ < 3) {
            try {
                Result result = sender.sendToUserAccount(message, account, RETRY_TIMES);

                LOG.info("[sendToUserAccount] target:{},title:{},result:{}", account, title, result);
                returnValue = ErrorCode.Success.getValue() == result.getErrorCode().getValue();
                break;
            } catch (Exception e) {
                LOG.error("[sendToUserAccount] error target:{},{}", account, e);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e1) {
                }
            }
        }
        LOG.info("[sendToUserAccount] target:{},title:{},returnValue:{}", account, title, returnValue);
        return returnValue;
    }

    public static void main(String args[]) {
        XiaomiPushService a = new XiaomiPushService();
        // device:android 5.1.1
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("orderId", 2745);
        msgMap.put("type", "deliver_money_exception");
        msgMap.put("shop_type", "ele");
        msgMap.put("book", false);
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("msg", JsonHelper.toJson(msgMap));
        extras.put("msgType", "order");
        String title = "新消息";
        // a.push(title, title, title, "b54b418f0e92f353c244504bd0dc7672",
        // "android 5.1.1", extras);

        Map<String, Object> msgMap1 = new HashMap<>();
        msgMap1.put("userId", 8);
        msgMap1.put("type", "on_line");
        msgMap1.put("uuid", "326F950D-8286-48D5-A4F2-8351CDFE1719");
        ExtMsg msg = new ExtMsg("user", msgMap1);
        String title1 = "新消息";
        a.sendToUserAccount(title1, title1, "e1e6c92183ed33f486c03fbf2a764906", "android 5.1.1", msg);
    }
}
